<?php
/**
 * Get the requested image and returns it as an base64 type
 * 
 * @author Sean
 * @return echos out a base64 encoded string
 */
 
include ("connect.php");
include ("config.php");

$GoogleID = $_GET['googleId'];
$GoogleID = mysql_real_escape_string($GoogleID);

$SessionID = $_GET['sessionId'];
$SessionID = mysql_real_escape_string($SessionID);

$thumbName = $_GET['thumbName'];
$thumbName = mysql_real_escape_string($thumbName);

$file = $pathToUsersFiles.$GoogleID."/thumbs/".$thumbName;

// Checks if the sessionid is valid
$result = mysql_query("SELECT sessionID FROM users WHERE GoogleID = '" . $GoogleID . "'");
while ($row = mysql_fetch_array($result)) {
   $DB_SessionID = $row["sessionID"];
}

// check if the fie exist
if (file_exists($file)){
	if($SessionID == $DB_SessionID){
		
		// Get the file extension
		$ext = end(explode('.', $thumbName));
		
		header('Access-Control-Allow-Origin: *');
		echo base64_encode_image($file,$ext);
	}
	else{
		header('Access-Control-Allow-Origin: *');
		header('Location: http://sean.servern.org/webdrop/Webdrop.html?#page=Login');
	}
}
else{
	header('Access-Control-Allow-Origin: *');
	echo "ERROR: File does not exist.";
}

/**
 * Encode the image to a base64 and return it
 * 
 * @author Sean
 */
function base64_encode_image ($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}

?>